//
//  AddNotesVController.m
//  Travel assistant
//
//  Created by lanou3g on 16/3/3.
//  Copyright © 2016年 旅游助手. All rights reserved.
//

#import "AddNotesVController.h"

@interface AddNotesVController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) HMTextView *textView;
@property (nonatomic, strong) HMComposePhotosView *photoView;
@property (nonatomic, strong) NotesRemindModel *notesRemindModel;
@end

@implementation AddNotesVController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setViews];
    [self setTextView];
    [self setComposePhotosView];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    // 成为第一响应者（叫出键盘）
    [self.textView becomeFirstResponder];
    
}
- (void)setViews{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.imageButton addTarget:self action:@selector(imageButtonAction:) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Upload_38.643147896879px_1183454_easyicon.net"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemAction:)];
}
- (void)rightBarButtonItemAction:(UIBarButtonItem *)sender{
    NSMutableArray *imageArr = [NSMutableArray array];
    self.notesRemindModel = [NotesRemindModel object];
    for (int i = 0; i < self.photoView.subviews.count; i++) {
        UIImageView *imV = self.photoView.subviews[i];
        CGSize imVSize = imV.image.size;
        /**设置图片大小*/
        imVSize.height = 120;
        imVSize.width = 60;
        imV.image = [self imageWithImage:imV.image scaledToSize:imVSize];
        //将我上传的图片存入数据中
        NSData *imageData = UIImagePNGRepresentation(imV.image);
        AVFile *imageFile = [AVFile fileWithName:[NSString stringWithFormat:@"image%d.png",i ] data:imageData];
        [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                NSLog(@"imageFile保存成功...");
            } else {
                NSLog(@"%@",error);
            }
        }];
        [imageArr addObject:imageFile];
    }
    
    [self.notesRemindModel setObject:imageArr forKey:@"imagesArray"];
    [self.notesRemindModel setObject:self.textView.text forKey:@"notes"];
    [self.notesRemindModel saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"self.notesRemindModel保存成功...");
        } else {
            NSLog(@"%@",error);
        }
    }];
}
////对图片尺寸进行压缩--

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

- (void)setTextView{
    // 1.创建输入控件
    CGRect backViewRect = self.backView.bounds;
    self.textView = [[HMTextView alloc] init];
    self.textView.alwaysBounceVertical = YES; // 垂直方向上拥有有弹簧效果
    self.textView.frame = CGRectMake(backViewRect.origin.x, backViewRect.origin.y, backViewRect.size.width, backViewRect.size.height - self.imageButton.bounds.size.height - 30);
    
    self.textView.delegate = self;
    
    // 2.设置提醒文字（占位文字）
    self.textView.placehoder = @"请输入备注...";
    // 3.设置字体
    self.textView.font = [UIFont systemFontOfSize:15];
    [self.backView addSubview:self.textView];
    
//    // 4.监听键盘
//    // 键盘的frame(位置)即将改变, 就会发出UIKeyboardWillChangeFrameNotification
//    // 键盘即将弹出, 就会发出UIKeyboardWillShowNotification
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//    // 键盘即将隐藏, 就会发出UIKeyboardWillHideNotification
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];


}
- (void)setComposePhotosView{
    self.photoView = [[HMComposePhotosView alloc] init];
    
    self.photoView.frame = CGRectMake(8, CGRectGetMinY(self.imageButton.frame) - 8, Screen_W - CGRectGetWidth(self.imageButton.frame) - 32, CGRectGetHeight(self.imageButton.frame));
    
    self.photoView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:self.photoView];
}
//#pragma mark - 键盘处理
///**
// *  键盘即将隐藏
// */
//- (void)keyboardWillHide:(NSNotification *)note
//{
//    // 1.键盘弹出需要的时间
//    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    // 2.动画
//    [UIView animateWithDuration:duration animations:^{
//        //self.toolBar.transform = CGAffineTransformIdentity;
//    }];
//}
//
///**
// *  键盘即将弹出
// */
//- (void)keyboardWillShow:(NSNotification *)note
//{
//    // 1.键盘弹出需要的时间
//    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    // 2.动画
//    [UIView animateWithDuration:duration animations:^{
//        // 取出键盘高度
//        CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//        CGFloat keyboardH = keyboardF.size.height - 30;
//        //self.toolBar.transform = CGAffineTransformMakeTranslation(0, - keyboardH);
//    }];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)imageButtonAction:(UIButton *)sender {
    NSLog(@"点击选取照片...判断是否登陆...");
    [self addSheetControllertWithTitle:@"选取照片"];
}
- (void)addAlertControllerWithTitle:(NSString *)title{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"请先登录..." preferredStyle:(UIAlertControllerStyleAlert)];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"跳转到登陆界面...");
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)addSheetControllertWithTitle:(NSString *)title{
    UIAlertController *sheetController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [sheetController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [sheetController addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"召唤神兽相册...");
        [self setImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
#pragma mark---选择照片---
        
        
        
        
        
        
        
    }]];
    [sheetController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"牌照...");
        [self setImagePickerController:UIImagePickerControllerSourceTypeCamera];
#pragma mark---拍照后选择照片---周一真机测试----
        
        
        
        
        
    }]];
    [self presentViewController:sheetController animated:YES completion:nil];
}

- (void)setImagePickerController:(UIImagePickerControllerSourceType)source{
    self.imagePicker = [[UIImagePickerController alloc]init];
    self.imagePicker.delegate = self;
    
    self.imagePicker.sourceType = source;
    //对图片进行大小位置选取
    [self.imagePicker setEditing:YES];
    self.imagePicker.allowsEditing = YES;
    //模态推出视图
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // 1.取出选中的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    
    
    
    
    
    // 2.添加图片到相册中
    if (self.photoView.subviews.count < 5) {
        [self.photoView addImage:image];
    } else {
        NSLog(@"提示最多添加5张图片............");
    }
    //UIImagePNGRepresentation   把图片转换成PNG的格式，不压缩 比较大
    //UIImageJPEGRepresentation  把图片转换成JPEG的格式，第二个参数填的是一个压缩的系数，一般是0.5
    //    _data = UIImageJPEGRepresentation(image, 0.5);
    [picker dismissViewControllerAnimated:YES completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
